package bean;

import bean.note.Bean;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;

class BeanDefinition {

    private final String name;

    private final Object config;

    private final Method method;

    private final  Class type;

    public BeanDefinition(String name, Object config, Method method) {
        this.name = name;
        this.config = config;
        this.method = method;
        type = method.getReturnType();
    }

     public String getName() {
         return name;
     }

     public Class getType() {
         return type;
     }

     public Object newObj(BeanFactory beanFactory)  {

        method.setAccessible(true);
        Object invoke = null;
        try {
            Parameter[] parameters = method.getParameters();
            ArrayList<Object> list = new ArrayList<>();
            for (Parameter parameter : parameters) {
                Bean annotation = parameter.getAnnotation(Bean.class);
                Object bean = null;
                if (annotation != null){
                    bean = beanFactory.getBean(annotation.value());
                }else {
                    bean = beanFactory.getBean(parameter.getType());
                }

                list.add(bean);
            }
            invoke = method.invoke(config,list.toArray());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return invoke;
    }
}
